<template>
  <div>
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="姓名" prop="username">
        <el-input v-model="form.username" />
      </el-form-item>
      <el-form-item label="num" prop="num">
        <el-button @click="setNum(-1)">点击--  {{ form.num }}</el-button>
        <el-button @click="setNum(1)">点击++  {{ form.num }}</el-button>
      </el-form-item>
      <el-form-item label="手机" prop="mobile">
        <el-input v-model="form.mobile" />
      </el-form-item>
      <el-form-item label="图形码" prop="code">
        <el-input v-model="form.code" />
        <span>1234</span>
        <button @click="getCode">获取验证码</button>
      </el-form-item>

    </el-form>
    <el-button @click="submit">确定提交</el-button>
  </div>
</template>
<script>
export default {
  data() {
    return {
      form: {
        username: '',
        num: 30,
        mobile: '',
        code: ''
      },
      rules: {
        username: [{ required: true, message: '必填', trigger: 'change' }],
        num: [{ required: true, message: '必填', trigger: 'change' }, {
          validator: (rule, value, callback) => {
            if (value < 30) {
              callback()
            } else {
              callback(new Error('num需要小于30'))
            }
          }
        }],
        mobile: [{ required: true, message: '必填', trigger: 'change' },
          { pattern: /^1[3-9]\d{9}$/, message: '请正确输入手机号', trigger: 'change' }
        ],
        code: [{ required: true, message: '必填', trigger: 'change' }]
      }
    }
  },
  methods: {
    async submit() {
      await this.$refs.form.validate()
    },
    setNum(step) {
      this.form.num = this.form.num + step
      // 触发当前的num的表单验证
      this.$refs.form.validateField(['num'], (errorMessage) => {
        console.log('errorMessage', errorMessage)
        // errorMessage:错误信息，验证通过：为空  验证失败：返回错误信息
        if (errorMessage === '') {
          console.log('验证成功')
        } else {
          console.log('验证失败')
        }
      })
    },
    getCode() {
      let xxx = 0
      this.$refs.form.validateField(['mobile', 'code'], (errorMessage) => {
        if (errorMessage === '') {
          xxx++
          if (xxx === 2) {
            console.log('验证真的成功了')
          }
        } else {
          console.log('验证失败')
        }
      })
    }
  }
}
</script>
<style>
</style>
